/*
 * @Author: pardon110
 * @Date: 2024-03-16 12:31:35
 * @LastEditors: pardon110@qq.com
 * @LastEditTime: 2024-03-16 17:50:58
 * @FilePath: \days7\web\context\ctx\engine.go
 * @Description:
 */
package ctx

import (
	"log"
	"net/http"
)

// 新定义
type HandlerFunc func(*Context)

type Engine struct {
	router *router
}

func New() *Engine {
	return &Engine{router: newRouter()}
}

// 转发到router实例具体实施
func (e *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
	log.Printf("Route %4s - %s", method, pattern)
	e.router.addRoute(method, pattern, handler)
}

// GET defines the method to add GET request
func (e *Engine) GET(pattern string, handler HandlerFunc) {
	e.addRoute("GET", pattern, handler)
}

// POST defines the method to add POST request
func (e *Engine) POST(pattern string, handler HandlerFunc) {
	e.addRoute("POST", pattern, handler)
}

// Run defines the method to start a http server
func (e *Engine) Run(addr string) (err error) {
	return http.ListenAndServe(addr, e)
}

// ServeHTTP implements http.Handler.
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 接收原始的http请求，响应对象
	c := newContext(w, r)
	e.router.handle(c)
}
